package com.ifonly.ext.freemarker.directive;

import com.ifonly.ext.freemarker.utils.DirectiveUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.util.Map;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-16 15:40
 * @since JDK 1.6
 */
public class BlockDirective implements TemplateDirectiveModel {
    public final static String DIRECTIVE_NAME = "block";

    @Override
    public void execute(Environment env,
                        Map params, TemplateModel[] loopVars,
                        TemplateDirectiveBody body) throws TemplateException, IOException {
        String name = DirectiveUtils.getRequiredParam(params, "name");
        TemplateDirectiveBodyOverrideWrapper overrideBody = DirectiveUtils.getOverrideBody(env, name);
        if (overrideBody == null) {
            if (body != null) {
                body.render(env.getOut());
            }
        } else {
            DirectiveUtils.setTopBodyForParentBody(env, new TemplateDirectiveBodyOverrideWrapper(body, env), overrideBody);
            overrideBody.render(env.getOut());
        }
    }

}
